#include "stdafx.h"
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "../Utils/Log.h"

namespace ja2{ namespace utils
{
	Log::Log(boost::filesystem::path const &FileName, bool LogToCout, FlushMode FlushMode_)
		:	m_FileName(FileName), m_Stream(m_FileName.string().c_str()), m_FlushMode(FlushMode_), m_BufferFlushSize(512), m_LogToCout(LogToCout)
	{
	}

	Log::~Log()
	{
		flush(true);
	}

	Log &Log::operator<<(std::string const &Right)
	{
		m_Buffer << Right;
		flush(false);

		return *this;
	}

	Log& Log::endl()
	{
		m_Buffer << std::endl;
		flush(false);

		return *this;
	}

	void Log::flush(bool Force)
	{
		if((Force || m_FlushMode == FM_IMMEDIATELY) || (m_FlushMode == FM_BUFFER && m_Buffer.tellp() > m_BufferFlushSize))
		{
			// String to write
			std::string const data = m_Buffer.str();
			// Write only if we have to
			if(data.size() > 0)
			{
				static bool first_write = true;
				// 1. write
				if(first_write)
				{
					// Get local time					
					time_t rawtime;
					time(&rawtime);
					// Write to stream
					m_Stream << " *** " << boost::posix_time::from_time_t(rawtime) << " *** " << std::endl << std::endl;

					first_write = false;
				}
				m_Stream << data;
				if(m_LogToCout)
					std::cout << data;
				m_Stream.flush();
				m_Buffer.str("");
				m_Buffer.clear();
			}
		}
	}
} /*utils*/} /*ja2*/